Passed
Pull Request — main (#12)
by Julia
03:31 queued 01:32
created

emp.js ➔ comparePasswords   A

Complexity

Conditions 4

Size

Total Lines 40
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 26
dl 0
loc 40
rs 9.256
c 0
b 0
f 0
cc 4
1
import bcrypt from "bcryptjs";
2
import jwt from "jsonwebtoken";
3
import { db } from "./db.js"
4
5
6
// separata modeller för emp och user eftersom
7
// inloggningen och registereringen fungerar annorlunda
8
// och checkToken funktionen kommer också skilja sig,
9
// dels ingen check för roll och dets lyfta ut idt och lägga till på req.body
10
const emp = {
11
    getOneFromDb: async function(username) {
12
        const result = await db.queryWithArgs(`CALL emp_login(?);`, [username]);
13
        const emp = result[0][0];
0 ignored issues
show
Unused Code introduced by
The constant emp seems to be never used. Consider removing it.
Loading history...
14
        return result[0][0];
15
    },
16
    checkToken: function(req, res, next, acceptableRoles=["admin"]) {
17
        let token = req.headers["x-access-token"];
18
19
        jwt.verify(token, process.env.JWT_SECRET, function (err, decoded) {
20
            if (err) {
21
                return res.status(500).json({
22
                    errors: {
23
                        status: 500,
24
                        source: "/login",
25
                        title: "Failed authentication",
26
                        detail: err.message
27
                    }
28
                });
29
            }
30
31
            // om inget token är med kommer det att kastas
32
            // ett fel här eftersom decoded inte kommer ha attributet role som alla token
33
            // som tillhör anställda ska ha
34
            if (!acceptableRoles.includes(decoded.role)) {
35
                // if unauthorized request it is safer
36
                // to make it look like the page does not
37
                // exist
38
                return res.status(404).json({
39
                    errors: {
40
                        status: 404,
41
                        source: req.originalUrl,
42
                        title: "Not found",
43
                        detail: "Page not found"
44
                    }
45
                });
46
            }
47
48
            req.emp = {
49
                id: decoded.id,
50
                role: decoded.role
51
            };
52
53
            console.log(req.emp);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
54
            return next();
55
        });
56
    },
57
58
    /**
59
     * @description Function that handles admin login
60
     *
61
     * @param {Request} req Request object
62
     * @param {Response} res Response object
63
     * @param {Function} next Next function
64
     *
65
     * @returns {Object} JSON object
66
     */
67
    login: async function login(req, res) {
68
        const username = req.body.username;
69
        const password = req.body.password;
70
71
        const emp = await this.getOneFromDB(username);
72
73
        // om användarnamn saknas kommer
74
        // databasen lyfta ett error
75
        // om lösenord saknas kommer det fångas i bcrypt compare
76
77
        return this.comparePasswords(res, password, emp);
78
    },
79
    /**
80
     * @description Function that compares passwords
81
     *
82
     * @param {Request} req Request object
83
     * @param {String} password Password
84
     * @param {Object} user User
85
     *
86
     * @returns {Object} JSON object
87
     */
88
    comparePasswords: function comparePasswords(res, password, emp) {
89
        bcrypt.compare(password, emp.hash, (err, result) => {
90
            if (err) {
91
                return res.status(500).json({
92
                    errors: {
93
                        status: 500,
94
                        source: "/login",
95
                        title: "bcrypt error",
96
                        detail: "bcrypt error"
97
                    }
98
                });
99
            }
100
101
            if (result) {
102
                const payload = {
103
                    id: emp.id,
104
                    role: emp.role 
105
                };
106
                const jwtToken = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: "24h" });
107
108
                return res.json({
109
                    data: {
110
                        type: "success",
111
                        message: "User logged in",
112
                        user: payload,
113
                        token: jwtToken
114
                    }
115
                });
116
            }
117
118
            return res.status(401).json({
119
                errors: {
120
                    status: 401,
121
                    source: "/login",
122
                    title: "Wrong password",
123
                    detail: "Password is incorrect."
124
                }
125
            });
126
        });
127
    }
128
};
129
130
export default emp;